package com.cxs.config;

import com.cxs.filter.JwtCheckTokenFilter;
import com.cxs.handler.JwtLoginSuccessHandler;
import com.cxs.handler.MyAccessDeniedHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @Author: CXS
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启方法级别的验证
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtLoginSuccessHandler jwtLoginSuccessHandler;

    @Autowired
    private JwtCheckTokenFilter jwtCheckTokenFilter;

    @Autowired
    private MyAccessDeniedHandler accessDeniedHandler;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 配置登录
     * 可以指定自己的userService
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin")
                .password(passwordEncoder.encode("admin"))
                .authorities("sys:query", "admin");
    }

    /**
     * 处理http请求
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        // 使用jwt 把session关掉
        http.sessionManagement().disable();
        // 设置前置过滤
        http.addFilterBefore(jwtCheckTokenFilter, UsernamePasswordAuthenticationFilter.class);
        // 设置拒绝访问的处理器 返回json
        http.exceptionHandling().accessDeniedHandler(accessDeniedHandler);
        http.formLogin()
                .loginProcessingUrl("/doLogin") // 给一个登录的执行路径 不需要写controller
                .successHandler(jwtLoginSuccessHandler) // 指定登录成功后走自己的处理器
                .permitAll()
                .and()
                .authorizeRequests()
                .anyRequest()
                .authenticated();
    }
}
